from PySide6.QtWidgets import QWidget,QAbstractItemView,QMenu,QTableWidgetItem,QMessageBox
from PySide6.QtCore import Qt
import pandas as pd
from sqlalchemy.orm import Session
from settings.publicvar import engine
from settings.publicFuncation.exceldownloadimport import OperationModel
from views.person.model.person import PersonBaseInfo,SurePersonType,PersonType
from views.person.surepersontype.surepersontype import Ui_item
from views.person.surepersontype.operationView import OperationView

class SurePersonTypeView(QWidget,Ui_item):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.itemtable.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.itemtable.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.itemtable.setContextMenuPolicy(Qt.CustomContextMenu)
        self.itemtable.customContextMenuRequested.connect(self.generate_menu)

        self.loadTableData()
        self.addbtn.clicked.connect(self.addFun)
        self.sereachedit.editingFinished.connect(self.serearchFun)
        self.serearchbtn.clicked.connect(self.serearchFun)
        self.downloadmodle.clicked.connect(self.downloadmodleFun)
        self.importbtn.clicked.connect(self.importdataFun)


        # 读取所有数据
    def loadTableData(self):
        with Session(engine) as session, session.begin():
            items = session.query(SurePersonType).all()
            self.setTableStructure(items)

    # 表格加载数据
    def setTableStructure(self, data):
        self.itemtable.setRowCount(len(data))
        for i, item in enumerate(data):
            idx = QTableWidgetItem(str(item.id))
            self.itemtable.setItem(i, 0, idx)
            name = QTableWidgetItem(item.personinfo.name)
            self.itemtable.setItem(i, 1, name)
            persontype = QTableWidgetItem(item.persontype.persontype)
            self.itemtable.setItem(i, 2, persontype)
            mark = QTableWidgetItem(item.mark)
            self.itemtable.setItem(i, 3, mark)

    def addFun(self):
        add = OperationView('add',False)
        add.exec()
        self.loadTableData()

    # 获取表单
    def generate_menu(self,pos):
        menu = QMenu()
        viewitem = menu.addAction('查看')
        changeitem = menu.addAction('修改')
        deleteitm = menu.addAction('删除')
        action = menu.exec(self.itemtable.mapToGlobal(pos))
        posrow = self.itemtable.currentRow()
        columns = self.itemtable.columnCount()
        data = [self.itemtable.item(posrow, i).text() for i in range(columns)]
        for i in range(columns):
            item = self.itemtable.item(posrow,i)
            if item is None:
                data.append('')
            else:
                data.append(item.text())
        if action == viewitem:
            view = OperationView('view', data)
            view.exec()
        elif action == changeitem:
            change = OperationView('change', data)
            change.exec()
        elif action == deleteitm:
            delete = OperationView('delete',data)
            delete.exec()
        self.loadTableData()

    # 搜索框数据处理
    def serearchFun(self):
        sereachdata = self.sereachedit.text().strip()
        if sereachdata == '':
            QMessageBox.critical(None, '错误', '搜索框不能为空！')
            self.loadTableData()
        else:
            with Session(engine) as session, session.begin():
                sereachName = session.query(PersonBaseInfo).filter(
                    PersonBaseInfo.name.like('%' + sereachdata + '%')).all()
                sereachIDcard = session.query(PersonBaseInfo).filter(
                    PersonBaseInfo.IDcard.like('%' + sereachdata + '%')).all()
                sereachiphone = session.query(PersonBaseInfo).filter(
                    PersonBaseInfo.iphone.like('%' + sereachdata + '%')).all()
                sereachData = sereachName + sereachIDcard + sereachiphone
                others = []
                if sereachData:
                    for personbase in sereachData:
                        for items in personbase.personinfos:
                            others.append(items)
                else:
                    QMessageBox.critical(None,'没有数据','你搜索数据不存在！')
                self.setTableStructure(others)

    def downloadmodleFun(self):
        OperationModel().downloadmodleFun('人员类型确定模板.xlsx')

    def importdataFun(self):
        items_names = ['idx','name','IDcard','persontype','mark']
        dtypes = {'IDcard': str}
        data = OperationModel().importdataFun(items_names,dtypes)
        with (Session(engine) as session,session.begin()):
            all_surepersontype = session.query(SurePersonType).all()
            all_name_id = [item.name_id for item in all_surepersontype]
            exist_personbase = session.query(PersonBaseInfo).filter(PersonBaseInfo.IDcard.in_(data.IDcard.to_list())).all()
            exist_persontype = session.query(PersonType).all()
            frame_persontype = [(item.id,item.persontype) for item in exist_persontype]
            if not exist_personbase:
                QMessageBox.critical(None,'失败','你导入的数据为空，不能导入空数据！')
            else:
                tem = []
                for item in exist_personbase:
                    tem.append((item.IDcard,item.id))
                exist_IDcard = [item[0] for item in tem]
                exist_personbase = pd.DataFrame(tem).rename(columns={1: 'name_id', 0: 'IDcard'})
                save_items = data[data['IDcard'].isin(exist_IDcard)]
                save_items = pd.merge(exist_personbase, save_items, on='IDcard').drop(
                    columns=['name', 'IDcard'])
                save_items = save_items[~save_items['name_id'].isin(all_name_id)]

                frame_persontype = pd.DataFrame(frame_persontype).rename(columns={0:'type_id',1:'persontype'})
                save_items = pd.merge(save_items,frame_persontype,on='persontype').drop(
                    columns=['persontype',]).to_dict('records')
                items = [SurePersonType(**item) for item in save_items]
                session.add_all(items)
                QMessageBox.information(None, '提示', '你导入成功%s条，失败%s条，明细如下！' % (len(items), len(data) - len(items)))
        self.loadTableData()